package com.jt.provider.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RefreshScope
@RestController
public class ProviderCacheController {
    @Value("${useLocalCache:true}")
    private boolean useLocalCache;

    @RequestMapping("/provider/cache01")
    public String doUseLocalCache01() {
        return "useLocalCache'value is   " + useLocalCache;
    }

    //---------------------------------------------------------
    //构建一个本地(Local)缓存对象(基于jvm中的一个对象存储从数据库获取的数据).
    private List<String> cache = new ArrayList<>();

    @RequestMapping("/provider/cache02")
    public List<String> doUseLocalCache02() {
        if (cache.isEmpty()) {
            synchronized (cache) {
                if (cache.isEmpty()) {//Thread-A,Thread-B,...
                    System.out.println("==Get data from database==");
                    //假设这部分分类信息是从数据库获取的,但是,我不希望每次获取分类信息都要从数据库查
                    List<String> cates = Arrays.asList("Category-A", "Category-B", "Category-C");
                    cache.addAll(cates);
                }
            }
        }
        return cache;
        }//生产层面
    }
